import 'package:flutter/material.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/store/config.dart';
import 'package:happy_elf_app/store/home.dart';
import 'package:happy_elf_app/utils/globalKey.dart';
import 'package:happy_elf_app/utils/themColor.dart';
import 'package:happy_elf_app/widgets/Toast/index.dart';

class Week extends StatefulWidget {
  const Week({super.key});

  @override
  State<Week> createState() => _WeekState();
}

class _WeekState extends State<Week> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  final HomeDataProvider = Provider.of<HomeData>(
    Global.navigatorKey.currentContext!,
    listen: false,
  );

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  List questionList = [
    {'content': '对做事情几乎没有兴趣或乐趣', 'score': 0, 'value': 1},
    {'content': '感到情绪低落、抑郁或绝望', 'score': 0, 'value': 2},
    {'content': '入睡困难、难以保持睡眠或睡得太多', 'score': 0, 'value': 3},
    {'content': '感到疲倦或精力不足', 'score': 0, 'value': 4},
    {'content': '食欲不振或暴饮暴食', 'score': 0, 'value': 5},
    {'content': '对自己感觉很糟糕——或者觉得自己是个失败者，辜负了自己或家人', 'score': 0, 'value': 6},
    {'content': '难以集中注意力做事情，例如读报或看电视', 'score': 0, 'value': 7},
    {
      'content': '行动或说话如此缓慢，以至于其他人可能已经注意到？或者相反-烦躁不安，动来动去比平时更多',
      'score': 0,
      'value': 8
    },
    {'content': '有过觉得自己不如死了或想以某种方式伤害自己的想法', 'score': 0, 'value': 9},
  ];

  // 处理评分点击事件
  void _onScoreSelected(int questionIndex, int selectedScore) {
    setState(() {
      questionList[questionIndex]['score'] = selectedScore;
    });
  }

  // 计算总分
  Map _calculateTotalScore() {
    Map data = {};
    for (int i = 0; i < questionList.length; i++) {
      // total += question['score'] as int;
      data[(i + 1).toString()] = questionList[i]['score'];
    }
    return data;
  }

  // 校验是否所有题目都已选择分数
  bool _checkAllQuestionsAnswered() {
    for (var question in questionList) {
      if (question['score'] == 0) {
        // 找到未答题，返回false
        return false;
      }
    }
    return true;
  }

  // 提交按钮点击事件
  void _onSubmit() async {
    if (_checkAllQuestionsAnswered()) {
      // 所有题目都已完成，展示总分
      final total = _calculateTotalScore();
      print('total${total}');
      var tar = HomeDataProvider.target;
      print('111$tar');
      var res = await Home().subReport({
        "targetId": HomeDataProvider.target['id'],
        'data': total,
      });
      print(res);
      if (res['code'] == 200) {
        Toast.show(context: context, message: '提交成功');
      }
    } else {
      // 存在未答题，提示用户
      Toast.show(context: context, message: '请完成所有题目后再提交');
      // 底部toast
      // ScaffoldMessenger.of(context).showSnackBar(
      //   SnackBar(
      //     content: const Text('请完成所有题目后再提交'),
      //     backgroundColor: hexColor('#E9614D'), // 提示条颜色与主题统一
      //     behavior: SnackBarBehavior.floating, // 悬浮样式，避免遮挡内容
      //     duration: const Duration(seconds: 2), // 提示显示时长
      //   ),
      // );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 540,
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12), color: hexColor('#FFF9F5')),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 300,
            padding: const EdgeInsets.symmetric(vertical: 6),
            decoration: BoxDecoration(
              color: hexColor('#E9614D'),
              borderRadius: BorderRadius.circular(28),
            ),
            child: const Center(
              child: Text(
                '第6周情绪评估',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
            ),
          ),
          SizedBox(height: 12),
          // 题目列表（可滚动）
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
              itemCount: questionList.length,
              itemBuilder: (context, index) {
                final question = questionList[index];
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 题目内容
                    Text(
                      '${question['value']}) ${question['content']}',
                      style: TextStyle(
                        color: hexColor('#010101'),
                        fontSize: 15,
                      ),
                    ),
                    const SizedBox(height: 10),

                    // 评分选择器（5个评分点）
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '几乎没有',
                          style: TextStyle(
                              fontSize: 14, color: hexColor('#666666')),
                        ),
                        Row(
                          children: List.generate(5, (scoreIndex) {
                            final currentScore = scoreIndex + 1; // 1-5分
                            return GestureDetector(
                              onTap: () =>
                                  _onScoreSelected(index, currentScore),
                              child: Container(
                                width: 28,
                                height: 28,
                                margin:
                                    const EdgeInsets.symmetric(horizontal: 6),
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: question['score'] >= currentScore
                                      ? Color.fromRGBO(233, 97, 77, 0.3)
                                      : Colors.white,
                                  border: Border.all(
                                    color: Color.fromRGBO(0, 0, 0, 0.4),
                                    width: 1,
                                  ),
                                ),
                              ),
                            );
                          }),
                        ),
                        Text(
                          '非常多',
                          style: TextStyle(
                              color: hexColor('#666666'), fontSize: 14),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                  ],
                );
              },
            ),
          ),
          // 提交按钮
          Container(
            width: 100,
            margin: EdgeInsets.only(left: 240),
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: hexColor('#E9614D'),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              onPressed: _onSubmit,
              child: const Text(
                '提交',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
              ),
            ),
          )
        ],
      ),
    );
  }
}
